package cn.song.order.service;

import cn.song.order.mapper.OrderMapper;
import cn.song.order.pojo.Order;
import co.song.feign.clients.UserClient;
import co.song.feign.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserClient userClient; // Feign替代RestTemplate
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过订单号查询订单 - 并使用restTemplate远程调用用户服务获取用户信息
     *
     * @param orderId 订单编号
     */
    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.远程查询user
        // String url = "http://localhost:8081/user/" + order.getUserId();
        // TODO 使用了@LoadBalanced注解，会自动使用轮询算法，从注册中心获取服务列表
        String url = "http://userservice:8081/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        // 3.存入order
        order.setUser(user);
        // 4.返回
        return order;
    }

    /**
     * 通过订单号查询订单 - 并使用restTemplate远程调用用户服务获取用户信息
     *
     * @param orderId 订单编号
     */
    public Order queryOrderById02(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.远程查询user
        User user = userClient.findById(order.getUserId());
        // 3.存入order
        order.setUser(user);
        // 4.返回
        return order;
    }
}
